package com.peanuts.tender.test;

public class Convert {
	
	private static byte charToByte(char c) {   
		return (byte) "0123456789ABCDEF".indexOf(c);   
	}
	
	
	/**
	 * 将16进制字符串转换成byte[] 数组
	 * **/
	public static byte[] hexStringToBytes(String hexString) {   
		if (hexString == null || hexString.equals("")) {   
			return null;   
		}   
		hexString = hexString.toUpperCase();   
		int length = hexString.length() / 2;   
		char[] hexChars = hexString.toCharArray();   
		byte[] d = new byte[length];   
		for (int i = 0; i < length; i++) {   
			int pos = i * 2;   
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));   
		}   
		return d;   
	}
	
	
	/**
	 * 将字节数组转换成16进制的字符串
	 * **/
	public static String bytesToHexString(byte[] src){   
		StringBuilder stringBuilder = new StringBuilder("");   
		if (src == null || src.length <= 0) {   
			return null;   
		}   
		for (int i = 0; i < src.length; i++) {   
			int v = src[i] & 0xFF;   
			String hv = Integer.toHexString(v);   
			if (hv.length() < 2) {   
				stringBuilder.append(0);   
			}   
			stringBuilder.append(hv);   
		}   
		return stringBuilder.toString();   
	}
	
	
	/**高低位**/
	public static byte[] gdlongtobyte(long a,int num){
		byte[] hh = new byte[num];
		long b;
		long c;
		for (int i = 0; i < num; i++) {
			b = a/256;
			c = a - b*256;
			hh[num-1-i] = (byte) (c);
			a = b;
		}
		return hh;
	}
	
	
	
	/** 
     * 左对齐（右方用空格填充） 
     *  
     * @param src 
     * @param width 
     * @return 
     */  
    public static String ljust(String src, int width,char fillchar) {  
        return expand(src, width,fillchar, true);  
    }  
  
    /** 
     * 右对齐（左方用空格填充）
     * @param src 
     * @param width 
     * @return 
     */  
    public static String rjust(String src, int width,char fillchar) {  
        return expand(src, width,fillchar, false);  
    }  
  
	/**
	 * 用于字符串左对齐和右对齐补位
	 * **/
	private static String expand(String src, int width, char fillchar, boolean postfix) {  
        String result = src;  
        if (result.length() < width) {  
            char[] temp = new char[width - result.length()];  
            for (int i = 0; i < temp.length; i++) {  
                temp[i] = fillchar;  
            }  
            if (postfix) {  
                result = result + new String(temp);  
            } else {  
                result = new String(temp) + result;  
            }  
        }  
        return result;  
    }

}
